<template>
  <view class="addFriend">
    <topTitle title="添加好友" />
    <view class="com">
      <search
        ref="searchComponent"
        @update:searchValue="searchFn"
        @confirmInput="searchAddFn"
      />
      <view v-if="searchValue">
        <view v-if="seachType == 0" @tap="searchAddFn" class="searchIcon">
          <i></i> 搜索：<text>{{ searchValue }}</text>
        </view>
        <view v-if="seachType == -1">
          <up-empty mode="search" text="該用戶不存在" marginTop="50">
          </up-empty>
        </view>
      </view>
      <view
        class="myAccount"
        v-if="!searchValue"
        @tap="goTo('/pages/create/myQrCode')"
        >我的ID：{{ userInfo.id_no }}<i></i
      ></view>

      <!--#ifdef APP-PLUS-->
      <view class="scanCode" @tap="scanCodeFn">
        <image src="@/static/image/21.png" mode="widthFix" />
        扫一扫
      </view>
      <!--#endif-->
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import { FriendInfoSelect } from "@/api/ImApi";
const instance = getCurrentInstance()?.appContext.config.globalProperties;

// 獲取用戶信息
let userInfo = ref<any>();
userInfo.value = uni.getStorageSync("userInfo");

let seachType = ref<number>(0);
let friendInfo = {};

// 搜索
let searchValue = ref<string>();
const searchFn = (e: any) => {
  seachType.value = 0;
  searchValue.value = e;
};

const searchComponent = ref<any>(null); // 获取子组件的引用
// 前往添加好友
const searchAddFn = () => {
  seachType.value = 0;

  FriendInfoSelect({ id_no: searchValue.value, loading: 1 })
    .then(async (e: any) => {
      console.log(e);
      seachType.value = 1;
      searchComponent.value?.clearSearchValue();
      friendInfo = { ...e, id_no: searchValue.value, type: 0 };
      let friendList = await instance?.$db.loadData("friendList", {
        user_id: e.user_id,
      });
   
      if (friendList.length) {
        instance?.goTo("/pages/chat/friendDetails?chatId=" + e.user_id);
      } else {
        instance?.goTo(
          "/pages/create/searchAdd?searchValue=" +
            encodeURIComponent(JSON.stringify(friendInfo))
        );
      }
    })
    .catch((e) => {
      seachType.value = -1;
    });
};

// 掃碼
const scanCodeFn = () => {
  uni.scanCode({
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      searchValue.value = res.result;
      searchAddFn();
    },
  });
};
</script>
<style scoped lang="scss">
@import "../../static/scss/addFriend.scss";
</style>
